package com.fzebu.fastboot.token;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzebu.fastboot.crypto.RSA;
import okhttp3.*;

import java.io.IOException;


/**
 * @author Y-Aron
 * @version 1.0.0
 * @create 2019/10/24 10:20
 */
public class TokenUtil {

    private static final String REGISTER_API = "/api/ec/dev/auth/regist";
    private static final String APPLY_TOKEN_API = "/api/ec/dev/auth/applytoken";
    private static final String APP_ID = "appid";
    private static final String CPK = "cpk";
    private static final String SECRET = "secret";
    private static final String TOKEN = "token";
    private static final String SSO_API = "/ssologin/getToken";
    private static final OkHttpClient httpClient = new OkHttpClient();

    public static String getSsoToken(String url, String appId, String loginId) throws IOException {
        url += SSO_API;
        HttpUrl urlBuild = HttpUrl
                .parse(url)
                .newBuilder()
                .addQueryParameter(APP_ID, appId)
                .addQueryParameter("loginid", loginId).build();
        Request request = new Request.Builder()
                .url(urlBuild)
                .get()
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 向ECOLOGY系统注册许可证
     * @param url       服务器地址
     * @param appId     许可证
     */
    public static TokenBean register(String url, String appId) throws IOException {
        url += REGISTER_API;
        String cpk = RSA.getPublicKey();
        Request request = new Request.Builder()
                .url(url)
                .addHeader(APP_ID, appId)
                .addHeader(CPK, cpk)
                .post(null)
                .build();
        Response response = httpClient.newCall(request).execute();
        JSONObject json = JSON.parseObject(response.body().string());
        json.put(SECRET, json.getString("secrit"));
        json.put(APP_ID, appId);
        return json.toJavaObject(TokenBean.class);
    }

    /**
     * 获取 token
     * @param url      服务器地址
     * @param tokenBean   token实体
     */
    public static String getToken(String url, TokenBean tokenBean) throws IOException {
        url += APPLY_TOKEN_API;
        String secretStr = tokenBean.getSecretStr();
        Request request = new Request.Builder()
                .addHeader(APP_ID, tokenBean.getAppId())
                .addHeader(SECRET, secretStr)
                .url(url)
                .post(new FormBody.Builder().build())
                .build();
        Response response = httpClient.newCall(request).execute();
        JSONObject json = JSON.parseObject(response.body().string());
        return json.getString(TOKEN);
    }
}
